
import * as Blockly from 'blockly/core'
import store from '@/store'
// 1-----打开窗口----------------------------------
const openModalJson = {
  type: 'open_modal',
  message0: '打开窗口 %1',
  args0: [
    // 动态生成选项
    {
      'type': 'input_dummy',
      'name': 'MODAl_INPUT'
    }
  ],
  extensions: ['dynamic_modal_extension'],
  style: 'action_blocks',
  previousStatement: true,
  nextStatement: true,
  // inputsInline: true,
  tooltip: '',
  helpUrl: '',
  mutator: 'modal_mutator'
}

Blockly.Extensions.register('dynamic_modal_extension',
  function () {
    this.getInput('MODAl_INPUT')
      .appendField(new Blockly.FieldDropdown(
        function () {
          var options = []
          // modal组件
          const comList = store.getters.getFormDataForMain?.template || []
          if (!comList.length) {
            options = [['没有数据', 'noData']]
            return options
          }
          for (var i = 0; i < comList.length; i++) {
            const com = comList[i]
            const dateString = com.name + '（' + com.key + '）'
            // var dateString = com.name
            options.push([dateString, com.key])
          }
          return options
        }), 'Modal')
  })

// Blockly.Extensions.register('modal_func_extension',
//   function () {
//     var that = this
//     const dropdown = new Blockly.FieldDropdown(
//       function () {
//         var options = []
//         // 获取component的选择框的值
//         // const list = store.getters.getFormList
//         // 获取组件的值，Component extension中的值
//         const compVar = that.getFieldValue('Modal')
//         if (!compVar || compVar === 'noData') {
//           options = [['没有数据', 'noData']]
//           return options
//         }
//         options.push(['打开窗口', 'open'])
//         options.push(['关闭窗口', 'close'])
//         return options
//       })
//     dropdown.setValidator(function (value) {
//       console.log('value setValidator')
//     })
//     // 生成extension的block
//     this.getInput('FUNC_INPUT')
//       .appendField(dropdown, 'Function')
//   })

// 创建积木
Blockly.Blocks['open_modal'] = {
  init: function () {
    this.jsonInit(openModalJson)
  }
}

/**
 * Mixin for mutator functions in the 'text_join_mutator' extension.
 * @mixin
 * @augments Blockly.Block
 * @package
 */
const mixinObj = {
  /**
   * Create XML to represent number of text inputs.
   * @return {!Element} XML storage element.
   * @this {Blockly.Block}
   */
  mutationToDom: function () {
    var container = Blockly.utils.xml.createElement('mutation')
    container.setAttribute('title', this.titleCount_)
    container.setAttribute('open', this.openCount_)
    container.setAttribute('close', this.closeCount_)
    return container
  },
  /**
   * Parse XML to restore the text inputs.
   * @param {!Element} xmlElement XML storage element.
   * @this {Blockly.Block}
   */
  domToMutation: function (xmlElement) {
    this.titleCount_ = parseInt(xmlElement.getAttribute('title'), 10) || 0
    this.openCount_ = parseInt(xmlElement.getAttribute('open'), 10) || 0
    this.closeCount_ = parseInt(xmlElement.getAttribute('close'), 10) || 0
    this.updateShape_()
  },
  /**
   * Populate the mutator's dialog with this block's components.
   * @param {!Blockly.Workspace} workspace Mutator's workspace.
   * @return {!Blockly.Block} Root block in mutator.
   * @this {Blockly.Block}
   */
  // 打开变异器弹窗的行为
  // decompose: function (workspace) {
  //   console.log('decompose')
  //   var containerBlock = workspace.newBlock('text_create_join_container')
  //   containerBlock.initSvg()
  //   // text_create_join_container 内含 input_statement Stack input
  //   var connection = containerBlock.getInput('STACK').connection
  //   console.log('titleCount_', this.titleCount_)
  //   if (this.titleCount_ && !containerBlock.getInput('modal_title')) {
  //     var titleBlock = workspace.newBlock('modal_title')
  //     titleBlock.initSvg()
  //     connection.connect(titleBlock.previousConnection)
  //     connection = titleBlock.nextConnection
  //   }
  //   if (this.openCount_) {
  //     var openBlock = workspace.newBlock('modal_open')
  //     openBlock.initSvg()
  //     connection.connect(openBlock.previousConnection)
  //     connection = openBlock.nextConnection
  //   }
  //
  //   if (this.closeCount_) {
  //     var closeBlock = workspace.newBlock('modal_close')
  //     closeBlock.initSvg()
  //     connection.connect(closeBlock.previousConnection)
  //     connection = closeBlock.nextConnection
  //   }
  //   return containerBlock
  // },
  /**
   * Reconfigure this block based on the mutator dialog's components.
   * @param {!Blockly.Block} containerBlock Root block in mutator.
   * @this {Blockly.Block}
   */
  // 变异器器弹窗的行为配置  并调用updateShape展示积木块
  // composeBack: function (containerBlock) {
  //   this.titleCount_ = 0
  //   this.openCount_ = 0
  //   this.closeCount_ = 0
  //   var itemBlock = containerBlock.getInputTargetBlock('STACK')
  //   // Count number of inputs.
  //   var connectionsTitle = []
  //   var connectionsOpen = []
  //   var connectionsClose = []
  //   while (itemBlock) {
  //     // 只能连一次
  //     if (itemBlock.type === 'modal_title') {
  //       if (!this.titleCount_) {
  //         this.titleCount_++
  //       }
  //       connectionsTitle.push(itemBlock.valueConnection_)
  //     }
  //     if (itemBlock.type === 'modal_open') {
  //       if (!this.openCount_) {
  //         this.openCount_++
  //       }
  //       connectionsOpen.push(itemBlock.valueConnection_)
  //     }
  //     if (itemBlock.type === 'modal_close') {
  //       if (!this.closeCount_) {
  //         this.closeCount_++
  //       }
  //       connectionsClose.push(itemBlock.valueConnection_)
  //     }
  //     itemBlock = itemBlock.nextConnection &&
  //       itemBlock.nextConnection.targetBlock()
  //   }
  //   // this.itemCount_ = connections.length
  //   this.updateShape_()
  //   // Reconnect any child blocks.
  //   if (connectionsTitle.length) {
  //     Blockly.Mutator.reconnect(connectionsTitle[0], this, 'model_title')
  //   }
  //   if (connectionsOpen.length) {
  //     Blockly.Mutator.reconnect(connectionsOpen[0], this, 'model_open')
  //   }
  //   if (connectionsClose.length) {
  //     Blockly.Mutator.reconnect(connectionsClose[0], this, 'model_close')
  //   }
  //   // for (var i = 0; i < this.itemCount_; i++) {
  //   //   Blockly.Mutator.reconnect(connections[i], this, 'ADD' + i)
  //   // }
  // },
  // compose: function (containerBlock) {
  //   this.titleCount_ = 0
  //   this.openCount_ = 0
  //   this.closeCount_ = 0
  //   var itemBlock = containerBlock.getInputTargetBlock('STACK')
  //   // Count number of inputs.
  //   var connections = []
  //   while (itemBlock) {
  //     connections.push(itemBlock.valueConnection_)
  //     if (itemBlock.type === 'modal_title') {
  //       this.titleCount_++
  //     }
  //     if (itemBlock.type === 'modal_open') {
  //       this.openCount_++
  //     }
  //     if (itemBlock.type === 'modal_close') {
  //       this.closeCount_++
  //     }
  //     itemBlock = itemBlock.nextConnection &&
  //       itemBlock.nextConnection.targetBlock()
  //   }
  //   this.updateShape_()
  // },
  /**
   * Store pointers to any connected child blocks.
   * @param {!Blockly.Block} containerBlock Root block in mutator.
   * @this {Blockly.Block}
   */
  saveConnections: function (containerBlock) {
    var itemBlock = containerBlock.getInputTargetBlock('STACK')
    var clauseBlock = itemBlock?.nextConnection?.targetBlock()
    while (clauseBlock) {
      switch (clauseBlock.type) {
      case 'modal_title':
        var inputTitle = this.getInput('modal_title')
        clauseBlock.valueConnection_ =
            inputTitle && inputTitle.connection.targetConnection
        break
      case 'modal_open':
        // var inputIf = this.getInput('IF' + i)
        var inputDo = this.getInput('modal_open')
        // clauseBlock.valueConnection_ =
        //   inputDo && inputDo.connection.targetConnection
        clauseBlock.valueConnection_ =
            inputDo && inputDo.connection.targetConnection
        break
      case 'modal_close':
        const inputDo1 = this.getInput('modal_close')
        clauseBlock.valueConnection_ =
            inputDo1 && inputDo1.connection.targetConnection
        break
      default:
        throw TypeError('Unknown block type: ' + clauseBlock.type)
      }
      clauseBlock = clauseBlock.nextConnection &&
        clauseBlock.nextConnection.targetBlock()
    }
    // var i = 0
    // while (itemBlock) {
    //   var input = this.getInput('ADD' + i)
    //   itemBlock.valueConnection_ = input && input.connection.targetConnection
    //   i++
    //   itemBlock = itemBlock.nextConnection &&
    //     itemBlock.nextConnection.targetBlock()
    // }
  },
  updateShape_: function () {
    if (this.titleCount_) {
      if (!this.getInput('modal_title')) {
        this.appendValueInput('modal_title').setCheck('String').appendField('设置标题')
      }
    } else {
      if (this.getInput('modal_title')) {
        this.removeInput('modal_title')
      }
    }
    if (this.openCount_) {
      if (!this.getInput('modal_open')) {
        this.appendValueInput('modal_open').setCheck('callback_function_expression').appendField('打开窗口回调')
      }
    } else {
      if (this.getInput('modal_open')) {
        this.removeInput('modal_open')
      }
    }
    if (this.closeCount_) {
      if (!this.getInput('modal_close')) {
        this.appendValueInput('modal_close').setCheck('callback_function_expression').appendField('关闭窗口回调')
      }
    } else {
      if (this.getInput('modal_close')) {
        this.removeInput('modal_close')
      }
    }
  }
}
const modalHelpFun = function () {
  this.titleCount_ = 1
  this.openCount_ = 1
  this.closeCount_ = 1
  this.updateShape_()
}
Blockly.Extensions.registerMutator('modal_mutator',
  mixinObj, modalHelpFun,
  ['modal_title', 'modal_open', 'modal_close'])

Blockly.JavaScript['open_modal'] = function (block) {
  const compVar = block.getFieldValue('Modal')
  const funcName = 'open'
  let code = `context.getModal('${compVar}').${funcName}({\n`
  if (block.titleCount_) {
    const title = Blockly.JavaScript.valueToCode(block, 'modal_title',
      Blockly.JavaScript.ORDER_COMMA) || '\'\''
    code = code + `title: ${title},\n`
  }
  if (block.openCount_) {
    const onOpen = Blockly.JavaScript.valueToCode(block, 'modal_open',
      Blockly.JavaScript.ORDER_COMMA) || '(tctx) => {}'
    code = code + `onOpen: ${onOpen},\n`
  }
  if (block.closeCount_) {
    const onClose = Blockly.JavaScript.valueToCode(block, 'modal_close',
      Blockly.JavaScript.ORDER_COMMA) || '(tcxt, args) => {}'
    code = code + `onClose: ${onClose}\n`
  }
  code = code + `})\n`
  return code
}

// ----------------------mutator中的组件，暂时不用---------------------------------------

const titleJson =
  {
    'type': 'modal_title',
    'message0': '设置标题 %1',
    'args0': [
      {
        'type': 'input_value',
        'name': 'TITLE',
        check: 'String'
      }
    ],
    'style': 'action_blocks',
    'previousStatement': null,
    'nextStatement': null,
    'check': 'String',
    'tooltip': '设置标题'
  }
// 创建积木
Blockly.Blocks['modal_title'] = {
  init: function () {
    this.jsonInit(titleJson)
  }
}

const openJson = {
  'type': 'modal_open',
  'message0': '打开回调 %1',
  'args0': [
    {
      'type': 'input_value',
      'name': 'modal_open'
    }
  ],
  'previousStatement': null,
  'nextStatement': null,
  'enableContextMenu': false,
  'style': 'action_blocks',
  'tooltip': ''
}

// 创建积木
Blockly.Blocks['modal_open'] = {
  init: function () {
    this.jsonInit(openJson)
  }
}

const closeJson = {
  'type': 'modal_close',
  'message0': '关闭回调 %1',
  'args0': [
    {
      'type': 'input_value',
      'name': 'modal_close'
    }
  ],
  'previousStatement': null,
  'nextStatement': null,
  'enableContextMenu': false,
  'style': 'action_blocks',
  'tooltip': ''
}

// 创建积木
Blockly.Blocks['modal_close'] = {
  init: function () {
    this.jsonInit(closeJson)
  }
}

// 2------关闭窗口-----------------------------------

const closeParamJson = {
  'type': 'modal_close_param',
  'message0': '参数 %1',
  'args0': [
    {
      'type': 'input_value',
      'name': 'MODAL_PARAM'
    }
  ],
  'previousStatement': null,
  'nextStatement': null,
  'enableContextMenu': false,
  'style': 'action_blocks',
  'tooltip': '关闭窗口回调的参数'
}
// 创建积木
Blockly.Blocks['modal_close_param'] = {
  init: function () {
    this.jsonInit(closeParamJson)
  }
}
const closeMixinObj = {
  /**
   * Create XML to represent number of text inputs.
   * @return {!Element} XML storage element.
   * @this {Blockly.Block}
   */
  mutationToDom: function () {
    var container = Blockly.utils.xml.createElement('mutation')
    container.setAttribute('param', this.paramCount_)
    return container
  },
  /**
   * Parse XML to restore the text inputs.
   * @param {!Element} xmlElement XML storage element.
   * @this {Blockly.Block}
   */
  domToMutation: function (xmlElement) {
    this.paramCount_ = parseInt(xmlElement.getAttribute('param'), 10) || 0
    this.updateShape_()
  },
  updateShape_: function () {
    if (this.paramCount_) {
      if (!this.getInput('modal_close_param')) {
        this.appendValueInput('modal_close_param').appendField('设置参数')
      }
    } else {
      if (this.getInput('modal_close_param')) {
        this.removeInput('modal_close_param')
      }
    }
  }
}
const helpFun = function () {
  this.paramCount_ = 0
  this.updateShape_()
}
Blockly.Extensions.registerMutator('close_modal_motator',
  closeMixinObj, helpFun,
  ['modal_close_param'])

const closeModalJson = {
  type: 'close_modal',
  message0: '关闭窗口 %1',
  args0: [
    {
      'type': 'input_dummy',
      'name': 'MODAl_INPUT'
    }
  ],
  extensions: ['dynamic_modal_extension'],
  previousStatement: true,
  nextStatement: true,
  inputsInline: true,
  style: 'action_blocks',
  mutator: 'close_modal_motator',
  tooltip: '',
  helpUrl: ''
}
// 创建积木
Blockly.Blocks['close_modal'] = {
  init: function () {
    this.jsonInit(closeModalJson)
  }
}

Blockly.JavaScript['close_modal'] = function (block) {
  const compVar = block.getFieldValue('Modal')
  const funcName = 'close'
  let code = `context.getModal('${compVar}').${funcName}(`
  const params = Blockly.JavaScript.valueToCode(block, 'modal_close_param',
    Blockly.JavaScript.ORDER_COMMA)
  code = code + `${params})\n`
  return code
}
